# -*- coding: utf-8 -*-
"""
Created on Tue Apr  7 10:55:23 2020

@author: wangpj
"""

import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn; seaborn.set()
import sys
#-------------------------------------------------
fp=sys.argv[1]
os.chdir(fp)
os.system("rm *dat")
def powspec(name):
    outname=name.split('.')[0]+".fps"
    os.system("powspec cfile1=%s window='-' dtnb=0.008 nbint=8100 nintfm=INDEF rebin=-1.03 plot=no outfile=%s norm=2" %(name,outname))
def eachfile(filepath):
    musicfile=[]
    pathdir=os.listdir(filepath)
    for s in pathdir:
        if os.path.isfile(s):     
            if os.path.splitext(s)[1]==".fps": 
                musicfile.append(s)
    return musicfile
def lcfile(filepath):
    lcurvefile=[]
    pathdir=os.listdir(filepath)
    for s in pathdir:
        if 'lc' in s:
            if os.path.isfile(s):     
                if os.path.splitext(s)[1]==".lc": 
                    lcurvefile.append(s)
    return lcurvefile
lc=lcfile(fp)
print('lc=',lc)
for j in lc:
	powspec(j)
fps=eachfile(fp)
print(fps)
Long=len(fps)
for i in fps:
    ff=i
    print('Start sed, i=%s'%i)
    os.system("sed -i '1s/.*/%s/' $TXT/fplot.txt" %(ff))
    os.system("sed -i '6s/.*/wdata %s.dat/' $TXT/fplot.txt" %(ff))
    print('Start fplot')
    os.system("fplot < $TXT/fplot.txt")
    os.system("sed -i '1,3d' %s.dat" %(ff))
    os.system('''cat %s.dat | awk '{print $1-$2" "$1+$2" "2*$3*$2" "2*$4*$2}' > %s.txt''' %(ff,ff))
    print('Start flx2xsp')
    os.system("flx2xsp %s.txt %s.pha %s.rsp" %(ff,ff,ff))
    os.system("cp pgplot.ps %s.ps"%(ff))

#os.system("rm -rf pgplot.ps")


